﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TUIO;

namespace GRIP.Gestures
{
    public class ZoomConstructor : GestureConstructor
    {
        public override void ConstructGestures(ContactFrameReadyEventArgs frame)
        {
            // Check if 1 drag exists, another one just got added
            if (DragA.ActiveGestures.Count == 1)
            {
                DragA ActiveDrag = DragA.ActiveGestures[0];
                List<GestureEvent<Gesture>> pendingEvents = Recognizer.PendingEvents;

                // Make sure it hasn't been removed
                for (int i = 0; i < pendingEvents.Count; i++)
                {
                    GestureEvent<Gesture> pendingEvent = pendingEvents[i];
                    if (pendingEvent.Gesture is DragA && pendingEvent.EventType == GestureEventType.Removed)
                        return;
                }
                
                // Check for a new one
                for (int i = 0; i < pendingEvents.Count; i++)
                {
                    GestureEvent<Gesture> pendingEvent = pendingEvents[i];
                    if (pendingEvent.Gesture is DragA && pendingEvent.EventType == GestureEventType.Added)
                    {
                        new ZoomGesture(frame.Time, Recognizer.GetNextId(), frame.AdapterSource, ActiveDrag, (DragA)pendingEvent.Gesture);
                        return;
                    }
                }
            }
                
            // Check if 2 drags just got added
            else if(DragA.ActiveGestures.Count == 0)
            {
                List<GestureEvent<Gesture>> pendingEvents = Recognizer.PendingEvents;
                for (int i = 0; i < pendingEvents.Count; i++)
                {
                    GestureEvent<Gesture> pendingEvent = pendingEvents[i];
                    // First one exists
                    if (pendingEvent.Gesture is DragA && pendingEvent.EventType == GestureEventType.Added)
                    {
                        // Check for a second one
                        for(int j = i+1; j < pendingEvents.Count; j++)
                        {
                            GestureEvent<Gesture> pendingEvent2 = pendingEvents[j];
                            // Slay them both for great justice
                            if (pendingEvent2.Gesture is DragA && pendingEvent2.EventType == GestureEventType.Added)
                            {
                                new ZoomGesture(frame.Time, Recognizer.GetNextId(), frame.AdapterSource, (DragA)pendingEvent.Gesture, (DragA)pendingEvent2.Gesture);
                                return;
                            }
                        }
                    }
                }
            }
        }
    }
}
